<template>
  <div class="order-detail-container">
    <!-- 头部 -->
    <div class="header">
      <button class="back-btn" @click="goBack">
        <i class="fas fa-arrow-left"></i>
      </button>
      <h1 class="page-title">订单详情</h1>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error-message">
      <i class="fas fa-exclamation-circle"></i>
      <p>{{ error }}</p>
      <button class="btn btn-primary" @click="fetchOrderDetail">
        重新加载
      </button>
    </div>

    <!-- 订单详情 -->
    <div v-else class="order-card">
      <!-- 订单头部信息 -->
      <div class="order-header">
        <div class="order-number">订单号: {{ order.orderNumber }}</div>
        <div class="order-status" :class="statusClass">
          {{ statusText }}
        </div>
      </div>

      <!-- 订单内容 -->
      <div class="order-content">
        <!-- 物品信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="fas fa-box"></i>
            物品信息
          </div>
          <div class="info-item">
            <div class="info-label">物品名称:</div>
            <div class="info-value">{{ order.title }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">价格:</div>
            <div class="info-value price-value">¥{{ order.price }}</div>
          </div>
          <div v-if="order.rentDays" class="info-item">
            <div class="info-label">租赁天数:</div>
            <div class="info-value">{{ order.rentDays }}天</div>
          </div>
        </div>

        <!-- 交易信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="fas fa-exchange-alt"></i>
            交易信息
          </div>
          <div class="info-item">
            <div class="info-label">卖家:</div>
            <div class="info-value">{{ order.sellerName }} ({{ order.sellerBuilding }}栋)</div>
          </div>
          <div class="info-item">
            <div class="info-label">买家:</div>
            <div class="info-value">{{ order.buyerName }} ({{ order.buyerBuilding }}栋)</div>
          </div>
        </div>

        <!-- 时间信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="fas fa-clock"></i>
            时间信息
          </div>
          <div v-if="order.startDate" class="info-item">
            <div class="info-label">开始时间:</div>
            <div class="info-value">{{ formatDate(order.startDate) }}</div>
          </div>
          <div v-if="order.endDate" class="info-item">
            <div class="info-label">结束时间:</div>
            <div class="info-value">{{ formatDate(order.endDate) }}</div>
          </div>
        </div>

        <!-- 订单状态信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="fas fa-info-circle"></i>
            订单状态
          </div>
          <div class="info-item">
            <div class="info-label">状态:</div>
            <div class="info-value">{{ statusText }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">订单ID:</div>
            <div class="info-value">{{ order.orderId }}</div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <!-- 待确认状态 - 买卖家都可操作 -->
        <template v-if="order.status === 1 /*&& isSeller*/">
          <button class="btn btn-primary" @click="confirmOrder">
            确认订单
          </button>
          <button class="btn btn-danger" @click="cancelOrder">
            取消订单
          </button>
        </template>

        <!-- 进行中状态 - 买家可操作 -->
        <template v-else-if="order.status === 2 && isBuyer">
          <button class="btn btn-success" @click="completeOrder">
            确认收货
          </button>
          <button class="btn btn-danger" @click="cancelOrder">
            取消订单
          </button>
        </template>


        <!-- 已取消状态 -->
        <template v-else-if="order.status === 4">
        </template>

        <!-- 通用按钮 -->
        <button class="btn btn-primary" @click="contactCounterparty(isSeller ? order.buyerId : order.sellerId)">
          联系{{ isSeller ? '买家' : '卖家' }}
        </button>
        <button class="btn btn-primary" @click="viewItem">
          查看物品详情
        </button>

      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from "@/utils/axios.ts";
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 订单数据
const order = ref({
  orderId: null,
  orderNumber: '',
  sellerId: null,
  sellerName: '',
  sellerBuilding: '',
  buyerId: null,
  buyerName: '',
  buyerBuilding: '',
  itemId: null,
  title: '',
  status: 0,
  rentDays: null,
  startDate: null,
  endDate: null,
  price: 0
})

// 加载状态和错误信息
const loading = ref(true)
const error = ref('')

// 当前用户ID（假设从全局状态获取）
const currentUserId = ref(null)

// 计算属性
const statusText = computed(() => {
  const statusMap = {
    1: '待确认',
    2: '进行中',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[order.value.status] || '未知状态'
})

const statusClass = computed(() => {
  return `status-${order.value.status}`
})

const isSeller = computed(() => {
  return currentUserId.value === order.value.sellerId
})

const isBuyer = computed(() => {
  return  currentUserId.value === order.value.buyerId

})

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    loading.value = true
    error.value = ''

    const orderId = route.params.id
    const response = await axios.get(`/api/itemOrders/getOrderById/${orderId}`)

    if (response.code === 200) {
      order.value = response.data
      console.log("order订单的信息：",order.value)
      ElMessage.success('订单详情加载成功')
    } else {
      error.value = response.msg || '获取订单详情失败'
      ElMessage.error(error.value)
    }
  } catch (err) {
    console.error('获取订单详情失败:', err)
    error.value = '获取订单详情失败，请稍后再试'
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 操作函数
const confirmOrder = () => {
  ElMessage.success('订单已确认')
  // 实际应用中应调用API
  order.value.status = 2 // 更新为进行中状态
}

const cancelOrder = () => {
  ElMessage.warning('订单已取消')
  // 实际应用中应调用API
  axios.post(`/api/itemOrders/cancelOrder/${order.value.orderId}/${order.value.status}`)
      .then(res => {
        if (res.code === 200){
          ElMessage.success('订单已取消')
        }else {
          ElMessage.error(res.data.mes)
        }
      })
  order.value.status = 4 // 更新为已取消状态
}

const completeOrder = () => {
  // 实际应用中应调用API
  axios.post(`/api/itemOrders/confirmRecover/${order.value.orderId}/${order.value.status}`)
      .then(res => {
        if (res.code === 200){
          ElMessage.success('订单已完成')
        }else {
          ElMessage.error(res.data.mes)
        }
      })
  order.value.status = 3 // 更新为已完成状态
}

const contactCounterparty = (friendId) => {
  ElMessage.info('已发送联系请求')
  router.push(`/Chat/${friendId}`)
}

const viewItem = () => {
  router.push(`/myItemDetail/${order.value.itemId}`)
}

// 初始化
onMounted(() => {
  // 获取当前用户ID
  axios.post("/api/users/getUserInfo")
      .then(res => {
        currentUserId.value = res.data.userId
      })

  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #1890ff;
  border-radius: 50%;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #e6f7ff;
}

.back-btn i {
  font-size: 18px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1890ff;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #e6f7ff;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading p {
  color: #595959;
  font-size: 16px;
}

.error-message {
  text-align: center;
  padding: 40px;
  color: #f5222d;
}

.error-message i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.error-message p {
  margin-bottom: 16px;
  font-size: 18px;
}

.order-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.order-number {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.order-status {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
}

.status-1 {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-2 {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-3 {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-4 {
  background-color: #fff1f0;
  color: #f5222d;
}

.order-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.info-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
  display: flex;
  align-items: center;
}

.section-title i {
  margin-right: 8px;
  color: #1890ff;
}

.info-item {
  display: flex;
  margin-bottom: 10px;
}

.info-label {
  width: 100px;
  color: #666;
  font-size: 14px;
}

.info-value {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.price-value {
  font-size: 24px;
  font-weight: 600;
  color: #f5222d;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

.btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.btn-primary {
  background: linear-gradient(135deg, #36cfc9 0%, #1890ff 100%);
  color: white;
}

.btn-primary:hover {
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
}

.btn-success {
  background: linear-gradient(135deg, #73d13d 0%, #52c41a 100%);
  color: white;
}

.btn-danger {
  background: linear-gradient(135deg, #ff7875 0%, #f5222d 100%);
  color: white;
}

.btn-warning {
  background: linear-gradient(135deg, #ffc53d 0%, #fa8c16 100%);
  color: white;
}

@media (max-width: 768px) {
  .order-content {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
  }

  .btn {
    width: 100%;
  }
}
</style>